from flask import Blueprint, render_template, flash, redirect, url_for, request, jsonify
from flask_login import current_user, login_required

from apps.forms.system_user_form import SystemUserForm, UpdateSystemUserForm
from rules.system_user_rule import search_system_user_with_page, create_system_user, describe_system_user_status, \
    search_system_user, describe_system_user

system_admin = Blueprint('system_admin', __name__, url_prefix='/system_admin')
ACTIVE = 'system'
ACTIVE_ITEM = 'system_admin'


@system_admin.route('/page', methods=['GET'])
@login_required
def page():
    page_index = request.args.get('page', 1, type=int)
    pagination = search_system_user_with_page(page_index)
    return render_template('system/page.html', pagination=pagination, active=ACTIVE,
                           active_item=ACTIVE_ITEM)


@system_admin.route('/create', methods=['POST', 'GET'])
@login_required
def create():
    form = SystemUserForm()
    if form.validate_on_submit():
        create_system_user(form, current_user)
        flash('新增成功', 'page_success')
        return redirect(url_for('system_admin.page'))
    return render_template('system/create.html', form=form, active=ACTIVE,
                           active_item=ACTIVE_ITEM)


@system_admin.route('/update_status', methods=['PUT'])
@login_required
def update_status():
    data = request.get_json()
    res_status = "success"
    res_msg = "修改成功"
    try:
        describe_system_user_status(data['id'], current_user)
    except Exception as e:
        res_status = "error"
        res_msg = "修改失败"
        print(e)
    return jsonify({"status": res_status, "msg": res_msg, "data": {}})


@system_admin.route('/edit/<int:id>', methods=['POST', 'GET'])
@login_required
def edit(id):
    user_orm = search_system_user(id)
    if request.method == 'GET':
        form = UpdateSystemUserForm(user_orm)
    else:
        form = UpdateSystemUserForm()
        form.username.data = user_orm.username

    if form.validate_on_submit():
        describe_system_user(id, form, current_user)
        flash('修改成功', 'page_success')
        return redirect(url_for('system_admin.page'))

    return render_template('system/edit.html', form=form, id=id, active=ACTIVE,
                           active_item=ACTIVE_ITEM)
